package com.stephen.redisdemo.atomic;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author: stephen
 * @create: 2020-02-29 17:24
 * @description: 同步队列
 * 队列中只会有一个元素,只有取出该元素才能往里放新的元素
 */
public class SynchronousBlockingQueueDemo {

    public static void main(String[] args) {
        BlockingQueue<String> queue = new SynchronousQueue<>();
        new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "\t put 1" );
                queue.put("1");

                System.out.println(Thread.currentThread().getName() + "\t put 2" );
                queue.put("2");

                System.out.println(Thread.currentThread().getName() + "\t put 3" );
                queue.put("3");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t1").start();

        new Thread(() -> {
            try {
                // 5秒钟之后再取
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "\t" + queue.take());

                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "\t" + queue.take());

                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "\t" + queue.take());

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t2").start();
    }
}
